package cn.bnjy.service.impl;

import cn.bnjy.common.WeiXinConstant;
import cn.bnjy.common.WeiXinAccessToken;
import cn.bnjy.common.WeiXinApi;
import cn.bnjy.entity.Menu;
import cn.bnjy.entity.WeiXinMenu;
import cn.bnjy.mapper.MenuMapper;
import cn.bnjy.service.IMenuService;
import cn.bnjy.util.CollectionUtils;
import cn.bnjy.util.HttpUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author chavin
 * @since 2018-11-03
 */
@Service
@Slf4j
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements IMenuService {

    @Autowired
    private MenuMapper menuMapper;

    @Override
    public boolean refreshMenu() {
        QueryWrapper<Menu> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", 1).orderByAsc("parent_id").orderByAsc("sort");
        List<Menu> menus = menuMapper.selectList(queryWrapper);
        if (CollectionUtils.isBlankList(menus)) {
            log.error("未查询到菜单数据");
            return false;
        } else {
            // 先构造一个有父子级关系的
            Map<String, Object> allMenuMaps = Maps.newLinkedHashMap();
            menus.forEach(menu -> {
                if (allMenuMaps.containsKey(String.valueOf(menu.getParentId()))) {
                    Map<String, Object> map = (Map<String, Object>) allMenuMaps.get(String.valueOf(menu.getParentId()));
                    List<Menu> list = (ArrayList) map.get("subMenus");
                    list.add(menu);
                } else {
                    Map<String, Object> map = Maps.newLinkedHashMap();
                    map.put("menu", menu);
                    map.put("subMenus", new ArrayList<Menu>());
                    allMenuMaps.put(String.valueOf(menu.getId()), map);
                }
            });

            // 构造有序集合
            Map<String, List<WeiXinMenu>> maps = Maps.newLinkedHashMap();
            List<WeiXinMenu> firstLevelMenus = Lists.newArrayList();
            allMenuMaps.forEach((k, v) -> {
                Map<String, Object> map = (Map<String, Object>) v;
                WeiXinMenu weiXinMenu = menu2WeiXinMenu((Menu)map.get("menu"));
                firstLevelMenus.add(weiXinMenu);
                List<Menu> list = (ArrayList) map.get("subMenus");
                if(!CollectionUtils.isBlankList(list)) {
                    List<WeiXinMenu> subButtons = Lists.newArrayList();
                    list.forEach(e -> {
                        subButtons.add(menu2WeiXinMenu(e));
                    });
                    weiXinMenu.setSub_button(subButtons);
                }
            });
            maps.put("button", firstLevelMenus);
            String json = JSON.toJSONString(maps);
            log.info("发送微信服务器创建菜单数据：{}", json);
            /*String result = HttpUtils.get(WeiXinApi.DELETE_MENU.replace(WeiXinConstant.ACCESS_TOKEN, WeiXinAccessToken.getToken()));
            JSONObject obj = JSON.parseObject(result);
            if(obj.getIntValue("errcode") != 0) {
                log.error("发送微信服务器删除菜单失败，返回值：{}", result);
                return false;
            }
            log.info("发送微信服务器删除菜单成功");*/
            String result = HttpUtils.post(WeiXinApi.CREATE_MENU.replace(WeiXinConstant.ACCESS_TOKEN, WeiXinAccessToken.getToken()), json);
            JSONObject obj = JSON.parseObject(result);
            if(obj.getIntValue("errcode") != 0) {
                log.error("发送微信服务器创建菜单失败，返回值：{}", result);
                return false;
            }
            log.info("发送微信服务器创建菜单成功：{}", json);
        }
        return true;
    }

    /**
     * 将menu转换为WeiXinMenu
     * @param menu
     * @return
     */
    private WeiXinMenu menu2WeiXinMenu(Menu menu) {
        WeiXinMenu weiXinMenu = new WeiXinMenu();
        weiXinMenu.setName(menu.getName());
        weiXinMenu.setType(menu.getType());
        weiXinMenu.setKey(menu.getClickKey());
        weiXinMenu.setUrl(menu.getUrl());
        weiXinMenu.setMedia_id(menu.getMedia_id());
        weiXinMenu.setAppid(menu.getAppid());
        weiXinMenu.setPagepath(menu.getPagepath());
        return weiXinMenu;
    }
}
